"""
1.插入背景图片  ok
2.全屏显示  ok  > tkinter_.attribute()
3.输出当前时间: Ok
4.文字内容提示：“准备开准备”  ok
5.自动关闭  ok > 通过多线程，创建一个子线程，延时发送关闭命令。
6.结束进程> 通过os.system()向cmd发送taskkill命令强行终止进程。

v1.0:基本完成上述功能。
"""
import random
from tkinter_ import *
import time
from tkinter_ import Tk
import threading
from PIL import Image, ImageTk
import os
import sys


def OpenExcel():
    """ open Excel Record your time of today """
    if (NowTame()[0] == 22 and NowTame()[1] >= 30) or (NowTame()[0] == 23):
        os.system(r"C:\Users\LCQ\Desktop\四六级AND考研\A_Log_for_Time.xlsx")
    return


def AutoClose():
    """ 向系统强制终止此进程的PID """
    for i in range(5):
        # 这里可以添加文字提示
        time.sleep(1)
    if NowTame()[0] >= 23:
        os.system("shutdown /a")
        os.system('shutdown /s /f /t 599 /c "23点就要睡觉啦！"')
    Pid = os.getpid()
    print(Pid)
    os.system(f"taskkill /f /pid {Pid}")
    root.destroy()


def NowTame():
    """ Get Localtime from system
     :return (int)time Hour and Minute
     """
    Time = time.localtime()
    TimeH = Time.tm_hour
    TimeM = Time.tm_min
    return TimeH, TimeM


def StrTime():
    """ :return 时间的字符串，格式xx点xx分 """
    ST = NowTame()
    return str(ST[0]) + "点" + str(ST[1]) + "分"


def Text():
    """
    :return: a string to background
    """
    if 22 <= NowTame()[0] < 23:
        AStr = "（入睡时间：0:00）\n" \
               "是今天最后一次“吃点东西、喝点水”的时间了\n" \
               "有半个小时的时间收拾一下正在做的事情\n" \
               "看看你得了多少时间金币"
    elif NowTame()[0] >= 23:
        AStr = "现在已经晚上11点了，此时是最后的通牒！\n" \
               "关电脑睡觉吧！\n" \
               "不要再让蓝光打扰你的睡眠\n" \
               "上床看看书、听听音乐。"
    else:
        AStr = "Error"
    return AStr


def PhotoPath():
    r""" 这段代码只能获取.jpg，.png不行（or的优先级高与is）
    :return 一个字符串 > 随机一张图片的绝对路径
     """
    # GoalDir = r"C:\Users\LCQ\OneDrive\图片\本机照片\Windows聚焦"
    Dir = r"C:\Users\LCQ\OneDrive\图片\本机照片\Good_Night"
    c = []
    a = os.walk(Dir)
    for stem, dirs, files in a:
        for file in files:
            path = os.path.join(stem, file)
            # print(path[-4:])
            try:
                if Image.open(path).size == (1920, 1080):
                    c.append(path)
            except OSError:
                pass
    print(c)
    return c[random.randint(0, len(c) - 1)]


if __name__ == "__main__":
    root: Tk = Tk()
    root.title("sleep")
    width = root.winfo_screenwidth()
    height = root.winfo_screenheight()
    root.geometry("%dx%d" % (width, height))
    root.attributes("-topmost", True, "-fullscreen", True)  # 窗口置顶
    # root.attributes(, True)  # 窗口最大化
    photo = Image.open(PhotoPath())  # 利用Image模块打开图
    photo = ImageTk.PhotoImage(photo)
    background = Label(root,
                       text=f"现在时间是{StrTime()}\n"
                            f"{Text()}",
                       font=("华文行楷", 25),  # 字体字号
                       fg="white",  # 前景色
                       image=photo,
                       justify=CENTER,  # 对齐方式
                       compound=CENTER, )  # 设置为背景
    background.pack()  # 背景绑定
    Open = threading.Thread(target=OpenExcel)
    Open.start()
    Timeout = threading.Thread(target=AutoClose)
    Timeout.start()

    root.mainloop()
    # os.system(f"taskkill /t /pid {PID}")
    sys.exit(0)
